#!/bin/bash

#
# Define mandatory variables.
#

set -e # Exit immediately if a command exits with a non-zero status.
set -u # Treat unset variables as an error.

#
# BASEIMAGE_DOCKER_REPO
#
# The Docker repository of the image being built.
#
# For Docker Hub Automated builds, the system defines the DOCKER_REPO
# environment variable, which stores the Docker repository of the image being
# built.  On travis, DOCKER_REPO environment variable is defined in the config
# file (.travis.yml).
#
BASEIMAGE_DOCKER_REPO=$DOCKER_REPO

#
# BASEIMAGE_DOCKER_TAG
#
# Tag of the image being built.
#
# For Docker Hub Automated builds, the system defines the DOCKER_TAG
# environment variable, which stores the tag of the Docker image being built.
# On travis, DOCKER_TAG environment variable is defined in the config file
# (.travis.yml).
#
BASEIMAGE_DOCKER_TAG=$DOCKER_TAG

#
# BASEIMAGE_IMAGE_NAME
#
# The Docker repository and tag of the image being built.
#
# This variable is a combination of BASEIMAGE_DOCKER_REPO and
# BASEIMAGE_DOCKER_TAG.
#
BASEIMAGE_DOCKER_IMAGE_NAME=$BASEIMAGE_DOCKER_REPO:$BASEIMAGE_DOCKER_TAG

#
# BASEIMAGE_DOCKER_IMAGE_VERSION
#
# Version of the Docker image being built.
#
# The image version is determined by the pushed Git tag that triggered the
# build.  On the Docker Hub Automated build system, the Git tag is stored in
# SOURCE_BRANCH.  On travis, since it is not pushing images to the repository,
# the docker image version is not important.  In this case, the image version
# is set to "dev".
#

GIT_TAG="${SOURCE_BRANCH:-dev}"

# Make sure the git tag has a format like:
#     v1.0.0
#     v0.1.0-beta
#     v2.0.0-rc
#     v2.0.0-rc2
if [[ "$GIT_TAG" =~ ^v[0-9\.]+(-(alpha|beta|rc)[0-9]*)?$ ]]; then
    # The image version is the git tag minus the leading 'v'.
    BASEIMAGE_DOCKER_IMAGE_VERSION="${GIT_TAG:1}"
elif  [[ "$GIT_TAG" = "dev" ]]; then
    # Special case for Travis/development builds.
    BASEIMAGE_DOCKER_IMAGE_VERSION="$GIT_TAG"
else
    echo "Invalid git tag: $GIT_TAG"
    exit 1
fi

unset GIT_TAG

